package org.example.controller;

import org.example.Dao.userDao;
import org.example.Entity.Student;
import org.example.Entity.User;
import org.example.Utils.MybatisUtils;
import org.example.Utils.PwdUtils;

import java.util.Objects;

public class UserOne {
    //判断是否重复及其登录查询校验
    public User select(String username) {
        userDao mapper = MybatisUtils.getMapper(userDao.class);
        User user = mapper.selectAccount(username);
        MybatisUtils.commit();
        return user;
    }

    //注册
    public int insert(String username, String password, String role) {
        String select = String.valueOf(select(username));
        int result;
        if (select.equals("null")) {
            //密码加密后合并到实体类中存入接口
            userDao mapper = MybatisUtils.getMapper(userDao.class);
            String Password = PwdUtils.getPwd(password);
            User user = new User();
            user.setUsername(username);
            user.setPassword(Password);
            user.setRole(role);
            int i = mapper.insertAccount(user);
            //事务提交并关闭链接
            MybatisUtils.commit();
            result = i;
        } else {
            result = 0;
        }
        return result;
    }

    //登录
    public int login(String username, String password) {
        User user = select(username);
        int result = 0;
        String pwd = PwdUtils.getPwd(password);
        //如果登录账号为未注册状态，则返回0
        if (Objects.isNull(user)) {
            result = 0;
        } else {
            String mysqlPwd = user.getPassword();
            String mysqlUserName = user.getUsername();
            if (username != null && username.equals(mysqlUserName) && pwd.equals(mysqlPwd)) {
                result = 1;
            }
        }
        return result;
    }
    //判断是学生还是老师   返回2表示是学生   返回0表示未注册
    public int selectStudent(String username) {
        userDao mapper = MybatisUtils.getMapper(userDao.class);
        int result = 0;
        User user = mapper.selectAccount(username);
        MybatisUtils.commit();
        if (Objects.isNull(user)) {
           result = 0;
        }else {
            String role = user.getRole();
            if (role.equals("老师")) {
                result = 1;
            }else if (role.equals("学生")){
                result = 2;
            }else {
                result = 0;
            }
        }
        return result;
    }
    //传递学号信息
    public Student selectStudents(String username) {
        userDao mapper = MybatisUtils.getMapper(userDao.class);
        Student student = mapper.selectStudent(username);
        MybatisUtils.commit();
        return student;
    }
}

